
//
//  StatusListViewModel.swift
//  VVbo
//
//  Created by Mr.Run on 2017/8/23.
//  Copyright © 2017年 Mr.Run. All rights reserved.
//

import Foundation
import SDWebImage

private let maxPullupTryTimes = 3

class StatusListViewModel {
    lazy var statusList = [StatusViewModel]()
    
    var pullupErrorTimes = 0
    
    //https://rm.api.weibo.com/2/remind/unread_count.json
    func loadStatus(pullup: Bool, completion:@escaping (_ isSuccess: Bool, _ shouldRefresh: Bool)->()) {
        
        if pullup && pullupErrorTimes > maxPullupTryTimes {
            completion(false, false)
            return
        }
        
        let since_id = pullup ? 0: (self.statusList.first?.status.id ?? 0)
        let max_id = !pullup ? 0 : (self.statusList.last?.status.id ?? 0)
        
        StatusListDAL.loadStatus(since_id: since_id, max_id: max_id) { (list, isSuccess) in
            
//        }
//        NetworkManager.shared().statusList(since_id: since_id, max_id: max_id) { (list, isSuccess) in
            
            if !isSuccess {
                completion(false, false)
                return
            }
            
            var array = [StatusViewModel]()
            
            for dict in list ?? [] {
                guard let model = Status.yy_model(with: dict) else{
                    continue
                }
                array.append(StatusViewModel(model: model))
            }
//            print(array)
//            guard let array = NSArray.yy_modelArray(with: Status.self, json: list ?? []) as? [Status] else{
//                completion(isSuccess, false)
//                return
//            }
//            print("刷新了\(self.statusList.count)数据")
            if pullup {
                self.statusList += array
            }else{
                self.statusList = array + self.statusList
            }
            
            if pullup && array.count == 0{
                self.pullupErrorTimes += 1
                completion(isSuccess, false)
            }else{
                self.cacheSingleImage(list: array, finished: completion)
//                completion(isSuccess, true)
            }
            
        }
    }
    
    private func cacheSingleImage(list:[StatusViewModel], finished:@escaping (_ isSuccess: Bool, _ shouldRefresh: Bool)->()) {
        var length = 0
        let group = DispatchGroup()
        
        for vm in list {
            if vm.picURLs?.count != 1 {
                continue
            }
            
            guard let pic = vm.picURLs?[0].thumbnail_pic,
                let url = URL(string: pic)
                else{
                continue
            }
            group.enter()
            SDWebImageDownloader.shared().downloadImage(with: url, options: [], progress: nil, completed: { (image, _, _, _) in
//                print(image ?? "")
                
                if let image = image,
                    let data = UIImagePNGRepresentation(image) {
                    length += data.count
                    vm.updateSingleImageSize(image: image)
                }
                
                group.leave()
            })
            
        }
        group.notify(queue: DispatchQueue.main) { 
//            print("图像缓存完成\(length/1024)k")
            finished(true, true)
        }
    }
    
}
